/*
 * mainwindow.cpp
 * 主窗口实现文件
 * 实现MainWindow类的成员函数，负责初始化界面和处理用户交互
 */
#include "mainwindow.h"
#include "ui_mainwindow.h"

#include "canttchartview.h"
#include "cantttimebaritem.h"
#include <QTimer>
#pragma execution_character_set("utf-8")

/**
 * @brief 将场景导出为PDF文件
 * @param view 图形视图指针
 */
void exportSceneToPdf(QGraphicsView* view);

/**
 * @brief 将图形视图导出为PDF文件
 * @param graphicsView 图形视图指针
 */
void exportGraphicsViewToPdf(QGraphicsView* graphicsView);

/**
 * @brief 将场景导出为图片文件
 * @param view 图形视图指针
 */
void exportSceneToImage(QGraphicsView* view);

/**
 * @brief MainWindow类的构造函数
 * @param parent 父窗口指针
 * @details 初始化UI，创建甘特图视图，设置时间范围，添加时间条和事件，并设置定时器导出PDF
 */
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    // 创建甘特图视图
    CanttChartView *view = new CanttChartView(this);

    // 设置时间轴范围和平台列表
    view->setAxisRange(QDateTime::fromString("2023-04-16 00:00:00", "yyyy-MM-dd hh:mm:ss"),
                       QDateTime::fromString("2023-04-18 00:00:00", "yyyy-MM-dd hh:mm:ss"),
                       QStringList() << "J-20230121" << "J-20230122" << "J-20230123");

    // 添加计划时间条和事件
    CanttTimeBarItem *item = view->addPlanTimeBar("J-20230121",
                         QDateTime::fromString("2023-04-16 03:00:00", "yyyy-MM-dd hh:mm:ss"),
                         QDateTime::fromString("2023-04-16 12:00:00", "yyyy-MM-dd hh:mm:ss"));
    item->addEvent(QDateTime::fromString("2023-04-16 05:00:00", "yyyy-MM-dd hh:mm:ss"), CanttTimeBarItem::TakeoffEvent);


    // 添加更多计划时间条和实际时间条
    view->addRealTimeBar("J-20230121",
                         QDateTime::fromString("2023-04-16 01:00:00", "yyyy-MM-dd hh:mm:ss"),
                         QDateTime::fromString("2023-04-16 13:00:00", "yyyy-MM-dd hh:mm:ss"));
    view->addPlanTimeBar("J-20230122",
                         QDateTime::fromString("2023-04-16 03:00:00", "yyyy-MM-dd hh:mm:ss"),
                         QDateTime::fromString("2023-04-16 18:00:00", "yyyy-MM-dd hh:mm:ss"));
    view->addRealTimeBar("J-20230122",
                         QDateTime::fromString("2023-04-16 05:00:00", "yyyy-MM-dd hh:mm:ss"),
                         QDateTime::fromString("2023-04-16 19:00:00", "yyyy-MM-dd hh:mm:ss"));
    view->addPlanTimeBar("J-20230123",
                         QDateTime::fromString("2023-04-16 00:00:00", "yyyy-MM-dd hh:mm:ss"),
                         QDateTime::fromString("2023-04-16 16:22:00", "yyyy-MM-dd hh:mm:ss"));
    view->addRealTimeBar("J-20230123",
                         QDateTime::fromString("2023-04-16 02:33:00", "yyyy-MM-dd hh:mm:ss"),
                         QDateTime::fromString("2023-04-16 18:45:00", "yyyy-MM-dd hh:mm:ss"));

    // 设置中心部件为甘特图视图
    setCentralWidget(view);

    // 最大化窗口
    showMaximized();

    // 设置定时器，2秒后导出PDF
	QTimer::singleShot(2000, this, [=]() {
		exportSceneToPdf(view);
		//exportGraphicsViewToPdf(view);
		//exportSceneToImage(view);
		});

}

/**
 * @brief MainWindow类的析构函数
 * @details 释放UI资源
 */
MainWindow::~MainWindow()
{
    delete ui;
}


#include <QFileDialog>
#include <QPrinter> 
#include <QPainter>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QMessageBox>
#include <QPageSize>
#include <QDir>
#include <QDesktopServices>
#include <QScreen>

void exportSceneToPdf(QGraphicsView* view)
{
	if (!view) return;

	QGraphicsScene* scene = view->scene();
	if (!scene) return;

	// 1. 选择保存目录
	QString saveDir = QFileDialog::getExistingDirectory(nullptr,
		QObject::tr("选择保存目录"),
		QDir::currentPath());
	if (saveDir.isEmpty()) return;
	
	QString filePath = QDir(saveDir).filePath(QString("output_%1.pdf").arg(QDateTime::currentDateTime().toString("yyyyMMdd_hhmmss")));

	// 2. 获取场景的矩形范围
	QRectF sceneRect = scene->sceneRect();   
	
	// 3. 配置打印机
	QPrinter printer(QPrinter::PrinterResolution);// PrinterResolution是 72 dpi。
	printer.setOutputFormat(QPrinter::PdfFormat);
	printer.setOutputFileName(filePath);
	/*
	PDF 内部用 1/72 inch = 1 point 作为坐标系。
	Qt的QPrinter / QPdfWriter  默认也是 72 dpi。
	*/
	//printer.setResolution(72);             // 必须 72，否则会缩放

	QPageSize pageSizePoint(QSizeF(sceneRect.width(), sceneRect.height()), QPageSize::Point);
	printer.setPageSize(pageSizePoint);
	printer.setPageMargins(QMarginsF(0, 0, 0, 0));   // 不留边

	// 4. 渲染
	QPainter painter(&printer);
	if (!painter.isActive()) {
		QMessageBox::warning(nullptr, QObject::tr("错误"),
			QObject::tr("无法创建 PDF 文件"));
		return;
	}

	// 场景左上角 (0,0) 对应 PDF 页面左上角
	scene->render(&painter,
		QRectF(0, 0, sceneRect.width(), sceneRect.height()),
		sceneRect);          // 源矩形
	painter.end();

	QMessageBox::information(nullptr, QObject::tr("成功"),
		QObject::tr("PDF 已保存至: %1").arg(filePath));

	QDesktopServices::openUrl(QUrl::fromLocalFile(filePath));
}


#include <QPdfWriter>
void exportGraphicsViewToPdf(QGraphicsView* graphicsView) {

	if (!graphicsView) return;

	QGraphicsScene* scene = graphicsView->scene();
	if (!scene) return;

	// 1.选择保存目录
	QString saveDir = QFileDialog::getExistingDirectory(nullptr, "选择保存目录", QDir::currentPath());
	if (saveDir.isEmpty()) return;
	QString filePath = QDir(saveDir).filePath(QString("output_%1.pdf").arg(QDateTime::currentDateTime().toString("yyyyMMdd_hhmmss")));

	// 2. 获取场景的矩形范围
	QRectF sceneRect = scene->sceneRect();
	QPageSize pageSizePoint(QSizeF(sceneRect.width(), sceneRect.height()), QPageSize::Point);

	// 初始化PDF写入器
	QPdfWriter pdfWriter(filePath);
	pdfWriter.setPageSize(pageSizePoint);
	/*
	PDF 内部用 1/72 inch = 1 point 作为坐标系。
	Qt的QPrinter / QPdfWriter  默认也是 72 dpi。
	*/
	pdfWriter.setResolution(72); // 必须 72，否则会缩放

	pdfWriter.setPageMargins(QMarginsF(0, 0, 0, 0));

	// 渲染场景到PDF
	QPainter painter(&pdfWriter);        
	if (!painter.isActive()) return;

	scene->render(&painter,
		QRectF(0, 0, sceneRect.width(), sceneRect.height()),
		sceneRect);          // 源矩形
	painter.end();

	QMessageBox::information(nullptr, "成功", "PDF已保存至: " + filePath);
	QDesktopServices::openUrl(QUrl::fromLocalFile(filePath));
}

void exportSceneToImage(QGraphicsView* view)
{
	if (!view) return;
	QGraphicsScene* scene = view->scene();
	if (!scene) return;

	/* 1. 选择保存路径 */
	QString saveDir = QFileDialog::getExistingDirectory(
		nullptr, QObject::tr("选择保存目录"), QDir::currentPath());
	if (saveDir.isEmpty()) return;

	QString filePath = QDir(saveDir).filePath(
		QString("scene_%1.png")          // 可改为 .jpg / .webp / .tiff
		.arg(QDateTime::currentDateTime().toString("yyyyMMdd_hhmmss")));

	/* 2. 场景逻辑矩形 */
	QRectF sceneRect = scene->sceneRect();
	if (sceneRect.isEmpty()) {
		QMessageBox::warning(nullptr, QObject::tr("警告"),
			QObject::tr("场景为空"));
		return;
	}

	/* 3. 分辨率 & 尺寸 */
	const qreal dpi = 300.0;                       // 想导出 300 dpi
	const qreal scale = dpi / 72.0;                // 放大倍数
	QSize imgSize(sceneRect.width() *4 + 0.5,
		sceneRect.height() * 4 + 0.5);

	/* 4. 创建大位图（ARGB32_Premultiplied 支持透明） */
	QImage img(imgSize, QImage::Format_ARGB32_Premultiplied);
	img.fill(Qt::transparent);                    // 背景透明
	img.setDevicePixelRatio(2);               // 让 Qt 知道这是高 DPI

	/* 5. 渲染 */
	QPainter painter(&img);
	painter.setRenderHint(QPainter::Antialiasing);
	painter.setRenderHint(QPainter::TextAntialiasing);
	scene->render(&painter,
		QRectF(0, 0, imgSize.width(), imgSize.height()),
		sceneRect);
	painter.end();

	/* 6. 保存磁盘 */
	if (!img.save(filePath, "PNG", 90)) {         // 90 是 PNG 压缩等级
		QMessageBox::warning(nullptr, QObject::tr("错误"),
			QObject::tr("保存失败"));
		return;
	}

	QMessageBox::information(nullptr, QObject::tr("成功"),
		QObject::tr("图片已保存至: %1").arg(filePath));
	QDesktopServices::openUrl(QUrl::fromLocalFile(filePath));
}
